package daphne.noterun.shader 
{
	import flash.display.Shader;
	import flash.events.Event;
	import flash.display.BitmapData;
	import flash.display.Shape;
	import flash.geom.Matrix;
	import flash.display.GradientType;
	import daphne.noterun.menus.Main;
	
	/**
	 * ...
	 * @author Daphne
	 */
	public class ShaderBin 
	{
		private var noteShaderProxy:ShaderProxy = null;
				
		public function ShaderBin()
		{
			generateNoteShader();
		}
		
		///-----------------------------
		//  GETTERS / SETTERS
		//------------------------------
		
		public function getNoteShader(centerX:Number, centerY:Number):Shader
		{
			if (noteShaderProxy == null)
				return null;
			else {
				noteShaderProxy.center = [centerX, centerY];
				return noteShaderProxy.shader;
			}
		}
		
		///-----------------------------
		//  SET UP
		//------------------------------
		private function generateNoteShader():void
		{
			noteShaderProxy = new ShaderProxy("Gradient.pbj");
			if (noteShaderProxy.shader == null) {
				noteShaderProxy.addEventListener(Event.COMPLETE, initShader);
			} else {
				initShader(null);
			}
		}
		
		/**
		* Draws the custom gradient with the shader.
		*/
		private function initShader(e:Event):void {
			trace("Shader init");
			noteShaderProxy.removeEventListener(Event.COMPLETE, initShader);
			
			var width:Number = Main.STAGE_WIDTH;
			var height:Number = Main.STAGE_HEIGHT;
			// center the gradient on the stage
			noteShaderProxy.center = [width/2, height/2];
			// passes a gradient in a bitmap to the shader
			noteShaderProxy.gradient = getGradient();
		}

		/**
		* Draws a linear gradient into a shape, then captures its bitmap data.
		*
		* @return Bitmap data with a horizontal linear gradient drawn into it.
		*/
		private function getGradient():BitmapData {
			// all the values for the gradient
			var colors:Array = [0xFF0000, 0xFF00FF, 0x0000FF, 0x00FFFF, 0x00FF00, 0xFFFF00, 0xFF0000];
			var alphas:Array = [1, 1, 1, 1, 1, 1, 1];
			var ratios:Array = [0, 38, 84, 125, 171, 214, 255];
			var matrix:Matrix = new Matrix();
			// gradient will be 360px wide to display all the colors in a 360 degree range;
			// height is unimportant for retrieving the colors, so it is made 1px high
			matrix.createGradientBox(360, 1);
			var shape:Shape = new Shape();
			shape.graphics.beginGradientFill(GradientType.LINEAR, colors, alphas, ratios, matrix);
			shape.graphics.drawRect(0, 0, 360, 1);
			shape.graphics.endFill();
			// draws gradient into bitmap data
			var bitmapData:BitmapData = new BitmapData(360, 1);
			bitmapData.draw(shape);
			return bitmapData;
		}
	}

}
